<template>
  <div>
    <div class="headerClass">
      <el-dialog
        title="图片上传"
        :visible.sync="uploading"
        width="30%"
      >
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :http-request="httpUploadMethod"
          :before-upload="beforeAvatarUpload"
          action=""
        >
          <img v-if="user.avatar" :src="avatarPrefix+user.avatar " class="avatar" alt="点击上传图片">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-dialog>
    </div>

    <el-card class="box-card  messageClass fontClass">
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <div slot="header" class="clearfix">
              <span style="    font-weight: bolder;font-size: 20px;">个人信息</span>
            </div>
            <Avatar
              class="avatar"
              :username="avatarName"
              :src="avatarPrefix+user.avatar "
              background-color="#ccc"
              color="white"
              style=" vertical-align: middle;"
              :inline="false"
              :size="avatarSize"
            />
            <div style="position: relative ;top:20px ;left: 50px "><el-button type="primary" icon="el-icon-upload" @click="uploading=true">上传头像</el-button></div>
          </div>
        </el-col>
        <el-col :span="12" style="margin-top: 20px">

          <div>
            <el-row :gutter="20" type="flex" justify="space-between">
              <div class="grid-content bg-purple">
                <div class="realNameClass test">
                  真实姓名：   <el-input v-model="user.realName" maxlength="10" show-word-limit />
                  <el-button slot="reference" style=" right: -67px;top: 40px;float: right;position: absolute;" type="primary" size="mini" icon="el-icon-edit" @click="handleClickRealName" />
                </div>
                <div class="areaClass test">
                  住址：  <el-input v-model="user.area" maxlength="30" show-word-limit />
                  <el-button slot="reference" style=" right: -67px;top: 40px;float: right;position: absolute;" type="primary" size="mini" icon="el-icon-edit" @click="handleClickArea" />
                </div>
                <div class="isHealthClass test">
                  健康状态：<el-tag v-if="user.isHealth===true" type="success">良好</el-tag> <el-tag v-else type="danger">危险</el-tag>
                </div>
                <div class="workRecordClass test">
                  <div v-if="user.role==='ROLE_USER'"> <p>出入次数：{{ user.recordNum }}</p> </div>
                  <div v-if="user.role==='ROLE_WORKER'"> <p>检测次数：{{ user.recordNum }}</p> </div>
                </div>
              </div>
              <div>
                <div class="relativeClass test">
                  <div><p>关联账号：{{ openId }}</p>
                    <el-popover
                      placement="right"
                      width="500"
                      trigger="click"
                    >
                      <img src="../../../assets/login/goto.jpg" alt="?">
                      <el-button slot="reference" style="    right: -22px;top: 17px;float: right;position: absolute;" type="primary" size="mini" icon="el-icon-edit" />
                    </el-popover>
                  </div>
                </div>
                <div class="createTimeClass test">
                  <div v-if="user.createdTime!==''||user.createdTime!==null"> <p>创建时间：{{ user.createdTime }}</p> </div>
                </div>
                <div class="updatedTimeClass test">
                  <div v-if="user.updatedTime!==''||user.updatedTime!==null"> <p>最近修改时间：{{ user.updatedTime }}</p> </div>
                </div>
                <div class="roleClass test">
                  <div v-if="user.role==='ROLE_ADMIN'">用户角色 ： <el-tag size="medium">管理员</el-tag></div>
                  <div v-else-if="user.role==='ROLE_WORKER'">用户角色 ： <el-tag size="medium">工作者</el-tag></div>
                  <div v-else-if="user.role==='ROLE_USER'">用户角色 ： <el-tag size="medium">用户</el-tag></div>
                  <div v-else><p>用户角色 ：获取账号角色失败,请联系客服</p></div>
                </div>
                <div class="nameClass test">
                  <div v-if="user.username!==null&&user.username!==''"><p>帐号昵称 ：{{ user.username }}</p> </div>
                  <a v-else><p>>帐号昵称 ：点击设置账号昵称</p></a>
                </div>
              </div>
            </el-row>
          </div>

        </el-col>
      </el-row>
    </el-card>
    <!--   查询用户出入记录   x轴 地点  y轴次数 -->
    <!--   查询工作者工作记录  x轴 地点  次数   -->
    <el-card style="width: 1600px!important;    margin: 50px auto; position: relative;">
      <div id="main" style="width: 1200px;height:700px;" />
    </el-card>
    <div style="display: flex">
      <el-card v-if="user.role==='ROLE_ADMIN'" style="width: 800px!important;    margin-top: 50px; margin-left: 40px;position: relative">
        <div id="main2" style="width: 800px;height:700px;" />
      </el-card>
      <el-card v-if="user.role==='ROLE_ADMIN'" style="width: 800px!important;    margin-top: 50px; margin-left: 40px;position:relative; ">
        <div
          style="    font-size: 20px;
    font-weight: bold;"
        >地区疫情排名</div>
        <el-table
          :data="tableData"
          style="width: 80%;margin:20px auto"
          height="550"
          :default-sort="{prop: 'num', order: 'descending'}"
        >
          <el-table-column
            type="index"
            width="50"
          />
          <el-table-column
            label="地区"
          >
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.name }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            sortable
            prop="num"
          >
            <template slot-scope="scope">
              <!--              <i class="el-icon-time" />-->
              <span style="margin-left: 10px">{{ scope.row.num }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="handleWatch(scope.$index, scope.row)"
              >查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-dialog title="详细信息" :visible.sync="areaRankVisiable">
        <el-table :data="areaRankInformation">
          <el-table-column property="rd" label="日期" width="150" />
          <el-table-column property="un" label="用户姓名" width="200" />
          <el-table-column property="wn" label="工作者姓名" width="150" />
          <el-table-column property="temperature" label="温度" width="150" />
          <el-table-column property="area" label="地址" />
        </el-table>
      </el-dialog>
      <!--      <el-button @click="areaRankVisiable=false">关闭</el-button>-->
    </div>

    <footer>
      =========================== Power  By =======================
      <br>
      <br>
      <br>
      吴经纶 张伟铭  郭锦锋
      <br>
      <br>
      <br>
      =========================== Power  By =======================
    </footer>
  </div>

</template>

<script>
import { mapGetters } from 'vuex'
import axios from 'axios'
import Avatar from 'vue-avatar'
import { getToken } from '@/utils/auth'
import moment from 'moment'
import request from '@/utils/request'
import { Message } from 'element-ui'
/**
 * @return {string}
 */

export default {
  name: 'DashboardWorker',
  components: { Avatar },
  data() {
    return {
      user: {
        id: '',
        createdTime: '',
        updatedTime: '',
        openId: '',
        username: '',
        role: '',
        avatar: '',
        realName: '',
        isHealth: '',
        area: '',
        recordNum: 0
      },
      avatarName: '无',
      avatarSize: 160,
      uploading: false,
      areaRankVisiable: false,
      fullscreenLoading: false,
      avatarPrefix: 'https://qcode-1300972980.cos.ap-guangzhou.myqcloud.com/',
      healthData: [],
      lineTitle: '标题',
      healthDataType: '单位',
      areaRankInformation: [],
      tableData: [{
        num: '4',
        name: '王小虎'
      }, {
        num: '3',
        name: '王小虎'
      }, {
        num: '2',
        name: '王小虎'
      }, {
        num: '1',
        name: '王小虎'
      }],
      alertLine: [],
      safeLine: [],
      totalLine: [],
      dayAlertNum: 0,
      daySafeNum: 0,
      todayRecordNum: 0,
      areaRank: []
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'role',
      'id',
      'openId',
      'real',
      'area',
      'createTime',
      'updatedTime',
      'isHealth',
      'avatar'
    ])
  },
  created() {
    this.imageUrl = this.avatar
    // alert(this.avatar)
    this.user.id = this.id
    this.user.createdTime = moment(this.createTime).format('YYYY-MM-DD')
    this.user.updatedTime = moment(this.updatedTime).format('YYYY-MM-DD')
    this.user.openId = this.openId
    this.user.username = this.name
    this.user.role = this.role
    this.user.avatar = this.avatar
    this.user.realName = this.real
    this.user.isHealth = this.isHealth
    this.user.area = this.area
    Message.info('欢迎您')
    const vm = this
    if (this.user.role === 'ROLE_USER') {
      this.lineTitle = '最近7天最高体温记录'
      this.healthDataType = '日期 ：温度'
      //  出入记录
      request({
        // url: 'https://localhost/api/user/recordnum',
        url: 'https://www.laozhoy1.club/api/user/recordnum',
        method: 'get'
      }).then(function(res) {
        console.log(res)
        if (res.code === 20000) {
          vm.user.recordNum = res.message
        }
      })
      // 健康记录数据
      request({
        // url: 'https://localhost/api/user/sevendaytemperature'
        url: 'https://www.laozhoy1.club/api/user/sevendaytemperature'
      }).then(function(res) {
        if (res.code === 20000) {
          console.log(res.message)
          vm.healthData = JSON.parse(res.message)
        }
      }).then(function() {
        vm.drawChart()
      })
    }
    if (this.user.role === 'ROLE_WORKER') {
      this.lineTitle = '最近7天检测记录'
      this.healthDataType = '日期 ：次数'
      // 出入记录
      request({
        // url: 'https://localhost/api/worker/recordnum',
        url: 'https://www.laozhoy1.club/api/worker/recordnum',
        method: 'get'
      }).then(function(res) {
        if (res.code === 20000) {
          vm.user.recordNum = res.message
        }
      })
      //  检测记录
      request({
        // url: 'https://localhost/api/worker/sevendaynum',
        url: 'https://www.laozhoy1.club/api/worker/sevendaynum',
        method: 'get'
      }).then(function(res) {
        if (res.code === 20000) {
          vm.healthData = JSON.parse(res.message)
        }
      }).then(function() {
        vm.drawChart()
      })
    }
    if (this.user.role === 'ROLE_ADMIN') {
      this.lineTitle = '最近7天检测记录'
      this.healthDataType = '日期 ：次数'
      request({
        // url: 'https://localhost/record/admin'
        url: 'https://www.laozhoy1.club/record/admin'
      }).then(function(res) {
        const data = JSON.parse(res.message)
        vm.dayAlertNum = data.dayAlertNum
        vm.daySafeNum = data.daySafeNum
        vm.todayRecordNum = data.todayRecordNum
        console.log(data.areaRank)
        console.log(data.areaRank[0])
        console.log(typeof data.areaRank[0])
        const result = []
        for (const i in data.areaRank) {
          result.push({ 'name': Object.keys(data.areaRank[i])[0], 'num': Object.values(data.areaRank[i])[0] })
        }
        console.log(result)
        vm.tableData = result
      }).then(function() {
        vm.drawAdminChart()
      })
      request({
        // url: 'https://localhost/record/sevenday'
        url: 'https://www.laozhoy1.club/record/sevenday'
      }).then(function(res) {
        const data = JSON.parse(res.message)
        vm.alertLine = data.alertLine
        vm.safeLine = data.safeLine
        vm.totalLine = data.totalLine
      }).then(function() {
        vm.drawAdminChartLine()
      })
    }
  },
  mounted() {
  },
  methods: {
    handleWatch(index, row) {
      console.log(row.name)
      const vm = this
      request({
        // url: 'https://localhost/record/area',
        url: 'https://www.laozhoy1.club/record/area',
        params: { 'area': row.name }
      }).then(function(res) {
        const list = JSON.parse(res.message)
        vm.areaRankInformation = list
      }).then(function() {
        vm.areaRankVisiable = true
      })
    },
    /**
     * @return {string}
     */
    GetDateStr(AddDayCount) {
      const dd = new Date()
      dd.setDate(dd.getDate() + AddDayCount)// 获取AddDayCount天后的日期
      const y = dd.getFullYear()
      const m = dd.getMonth() + 1// 获取当前月份的日期
      const d = dd.getDate()
      return y + '-' + m + '-' + d
    },
    drawChart() {
      const myChart = this.$echarts.init(document.getElementById('main'))

      const option = {
        title: {
          text: this.lineTitle
        },
        tooltip: {},
        legend: {
          data: [this.healthDataType]
        },
        xAxis: {
          type: 'category',
          data: [this.GetDateStr(-6),
            this.GetDateStr(-5),
            this.GetDateStr(-4),
            this.GetDateStr(-3),
            this.GetDateStr(-2),
            this.GetDateStr(-1),
            this.GetDateStr(0)]
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '60%']
        },
        series: [
          {
            name: this.healthDataType,
            type: 'line',
            connectNulls: true,
            data: this.healthData,
            label: {
              show: true
            }
          }
        ],
        grid: {
          left: '30%'
        }
      }
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option)
    },
    drawAdminChartLine() {
      const myChart = this.$echarts.init(document.getElementById('main'))

      const option = {
        title: {
          text: this.lineTitle
        },
        tooltip: {},
        legend: {
          show: true,
          data: ['正常体温人数', '危险体温人数', '检测人数']
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          data: [this.GetDateStr(-6),
            this.GetDateStr(-5),
            this.GetDateStr(-4),
            this.GetDateStr(-3),
            this.GetDateStr(-2),
            this.GetDateStr(-1),
            this.GetDateStr(0)]
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '60%']
        },
        series: [
          {
            name: '正常体温人数',
            type: 'line',
            connectNulls: true,
            data: this.safeLine,
            smooth: true,
            label: {
              show: true
            }
          },
          {
            name: '危险体温人数',
            type: 'line',
            connectNulls: true,
            data: this.alertLine,
            smooth: true,
            label: {
              show: true
            }
          },
          {
            name: '检测人数',
            type: 'line',
            connectNulls: true,
            data: this.totalLine,
            smooth: true,
            label: {
              show: true
            }
          }
        ],
        grid: {
          left: '30%'
        }
      }
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option)
    },
    drawAdminChart() {
      const myChart = this.$echarts.init(document.getElementById('main2'))
      const option = {
        title: {
          text: '大数据分析图'
        },
        tooltip: {},
        legend: {
          data: ['平均每日体温超标的人数', '平均每日体温正常的人数', '今日检测总人数']
        },
        xAxis: {
          type: 'category',
          data: ['平均每日体温超标的人数', '平均每日体温正常的人数', '今日检测总人数']
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '60%']
        },
        series: [
          {
            name: '人数',
            type: 'bar',
            connectNulls: true,
            data: [this.dayAlertNum, this.daySafeNum, this.todayRecordNum],
            label: {
              show: true
            }
          }
        ],
        grid: {
        }
      }
      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option)
    },
    handleClickRealName: function() {
      const loading = this.$loading({ fullscreen: true })
      request({
        // url: 'https://localhost/api/fixrealname',
        url: 'https://www.laozhoy1.club/api/fixrealname',
        method: 'get',
        params: { 'realName': this.user.realName }
      }).then(function(res) {
        loading.close()
        if (res.code === 20000) {
          Message.info('修改成功')
        } else {
          Message.error('修改失败')
        }
      })
    },
    handleClickArea: function() {
      const loading = this.$loading({ fullscreen: true })
      request({
        // url: 'https://localhost/api/fixarea',
        url: 'https://www.laozhoy1.club/api/fixarea',
        method: 'get',
        params: { 'area': this.user.area }
      }).then(function(res) {
        loading.close()
        if (res.code === 20000) {
          Message.info('修改成功')
        } else {
          Message.error('修改失败')
        }
      })
    },
    httpUploadMethod: function(data) {
      console.log(data)
      const file = data.file
      const formData = new FormData()
      const token = getToken()
      formData.append('file', file)
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': token
        }
      }
      const vm = this
      // https://localhost/api/avatar
      axios.post('https://www.laozhoy1.club/api/avatar', formData, config)
        .then(function(res) {
          console.log(res)
          vm.user.avatar = res.data.message
          vm.uploading = false
          window.location.reload()
        })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped>
  footer {
    height: 100px;
    background: #FFFFFF;
    margin-top: 80px;
    text-align: center;
  }
  .isHealthClass{
    width: 200px;
    margin: 8px 0px;
  }
  .workRecordClass{
    width: 200px;
  }
  .areaClass{
    width: 400px;
    position: relative;
  }
  .realNameClass{
    position: relative;
    width: 200px;
  }
  .messageClass{
    width: 1600px!important;
    position: relative;
    margin: auto;
    height: 310px;
    top: 30px;
  }
  .text-center{
    text-align: center;
  }
  .avatar{
    margin-left:30px;
  }
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 480px;
  }
  .test{
    /*border: black 1px solid;*/
    /*float: right;*/
  }
  .el-menu-item{
    margin-left: 80px;
  }
  .el-menu{
    padding-left: 548px;
  }
  .fontClass{
    font-family: "Arial","Microsoft YaHei","黑体","宋体",sans-serif;
    font-size:13px;
    color:#5f5f5f;
    line-height:35px;
    text-transform:uppercase
  }
  .headerClass{
    position: relative;
    width: 201px;
    margin: auto
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .navigation{
    position: relative;
    top: 36px;
  }
  .functionArea{
    position: relative;
    top: 36px;
  }
</style>
